#include "client.h"

int getsfile(int netfd,char *filename){
    ssize_t fileLength=0;
    printf("%s\n",filename);
    int fd=open(filename,O_RDWR|O_CREAT|O_TRUNC,0666);
    ERROR_CHECK(fd,-1,"open");
    printf("i am here\n");
    struct stat statbuf;
    fstat (fd,&statbuf);
    fileLength =  statbuf.st_size;

    if(fileLength!=0){
        lseek(fd,fileLength-1,SEEK_SET);
    }
    send(netfd,&fileLength,sizeof(ssize_t),MSG_NOSIGNAL);
    int length;                                                                     
    off_t filesize=0;
    recvn(netfd,&filesize,sizeof(int));
    //filesize是总长度
    off_t cursize = 0;
    //off_t slice = filesize/1000;
    off_t slice =0; 
    off_t lastsize = 0;  
    char buf[1024] = {0};
   while(1){
        length =0; 
        recvn(netfd,&length,sizeof(int));
        if(length == 0){ 
            break;
        }
        bzero(buf,sizeof(buf));
        recvn(netfd,buf,length);
        cursize += length;
        if(cursize - lastsize > slice){
            printf("%5.2lf%%\r",100.0 * cursize / filesize);
            fflush(stdout);
            lastsize = cursize;
        }
        write(fd,buf,length);
        printf("%s\n",buf);
    }
    printf("100.00%%\n");
    printf("下载完成\n");
    close(fd);
    return 0;
}

